package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.CreateResultXML;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskConfig;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class TaskResultTD extends GeneralTestWidget {

	private WlanManager wlanManager;

    private LinearLayout httptaskLayout;
    private LinearLayout ftptaskLayout; 
    private LinearLayout pingtaskLayout;  
    //private LinearLayout snrtaskLayout;
    private LinearLayout rssitaskLayout;

    private String cameraFlag= "";
    private boolean isShow = false;

//	private ActivityBroadcastReceiver myReceiver;
    private Activity ctx;
    private Task task;
    private Button backBtn;
    private Button btnDraw;
    private LinearLayout taskNumLayout;
    private Handler handler;
    private String fileName;
    private Button btnPic;
    private Thread thread;
	private boolean connected = false;
	private boolean connected2 = false;
//    private Button uploadButton;
    public TaskResultTD(Activity context) {
        super(context);
        inflate(context, R.layout.task_result_widget_td, this);
        this.ctx = context;
        wlanManager = new WlanManager(ctx);
        httptaskLayout = (LinearLayout) this.findViewById(R.id.httpTaskFinishLayout_td);
        ftptaskLayout = (LinearLayout) this.findViewById(R.id.ftpTaskFinishLayout_td); 
        pingtaskLayout = (LinearLayout) this.findViewById(R.id.pingTaskFinishLayout_td); 
        //snrtaskLayout = (LinearLayout) this.findViewById(R.id.snrTaskFinishLayout_td);
        rssitaskLayout = (LinearLayout) this.findViewById(R.id.rssiTaskFinishLayout_td); 
 
   //     task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK); 
        task = GlobalApp.taskTD;
        
        cameraFlag =(String)ctx.getIntent().getSerializableExtra(TAG_CAMERA_FLAG); 
        ctx.getIntent().putExtra(TAG_CAMERA_TASK, task);
        SharedPreferences settings = ctx.getSharedPreferences(MyMobileCfgWidget.PREFS_NAME, 0);
        String tel = settings.getString(MyMobileCfgWidget.PREFS_KEY, "");
        task.testPhone = tel;
        initTask(task,ctx,task.selNetType);
        task = dealWebAndPeapData(task);
        boolean tempResult = false;

        tempResult = false; 
        int tempNum = 0;
        for(int i=0;i< GlobalApp.taskTestList.size();i++){
        	if ( GlobalApp.taskTestList.get(i).id == task.id) {
        		tempResult = true;
        		break;
			}
        	tempNum ++;
        } 
        if(! tempResult)
        	GlobalApp.taskTestList.add(task);
        else  
        	GlobalApp.taskTestList.set(tempNum, task); 
        
        taskNumLayout = (LinearLayout) this.findViewById(R.id.taskNumLayout_td);
        backBtn = (Button) this.findViewById(R.id.task_result_btnBack_td);
        btnDraw = (Button) this.findViewById(R.id.btn_draw_td);
        btnPic = (Button)this.findViewById(R.id.btnpic_td);
        if (GlobalApp.DEBUG) {
			System.out.println("taskresultTD 测试类型" + GlobalApp.getTestType());
		}
        if (GlobalApp.getTestType() != 1) {
			btnPic.setVisibility(View.VISIBLE);
		}else {
			btnPic.setVisibility(View.GONE);
		}
        
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	back_button();
            }
        });
        btnPic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	GlobalApp.who_to_CameraWidget = MessageWhat.TaskResultTD;
                CameraWidget cw = new CameraWidget(ctx);
               try {
            	   ctx.setContentView(cw);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("CameraShow", e.getMessage());
				}
            }
        });
        btnDraw.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != fileName) {
                    showMessage(ctx, "正在重新上传中...");
                    new Thread() {
                        public void run() {
                           if (uplod(fileName, ctx, handler))
                                {
                        	   		fileName = null;
                                }
                        	System.out.println("======================暂时不上传");
                        }
                    }.start();
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
               //  shotScreen();
            }   
        });
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_SUCESS_CONNECTED:  
					dismissMessageDialog();
                	upload();
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    showMessage(ctx, "无法获取FTP账号");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                	if(cameraFlag != null && cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) {
                		System.out.println("--------------  说好的拍照呢 ？ 上传成功 。 。 。  ---------------");
                		
                	} else {
                		showMessage(ctx, "上传成功.");
	                    int value = ctx.getIntent().getIntExtra(MessageWhat.INDEX_TaskResultTD_WIDGET, 0);
	            		if (value == 1) {
	            			if(GlobalApp.getTestType() !=1)
	            			 showCameraDialog(ctx);
	            		}
                	}
            			
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    showMessage(ctx, "上传失败");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    showMessage(ctx, "FTP登录失败");
                    break;
                }
            }
        }; 
        wlanManager.setHandler(handler); 
        show();
        if(cameraFlag == null || !cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) 
        	connectNetWork();  
        ctx.getIntent().putExtra(TAG_REFER_RESULT_FLAG, TAG_REFER_RESULTTD);
    }

    private void connectNetWork(){
		   showMessageDialog(ctx, "正在连接网络..."); 
		   thread = new Thread() { 
		        @Override
		        public void run() {
		        	if(wlanManager.checkNetworkType() != 1 && wlanManager.checkNetworkType() != 5){
		        		wlanManager.closeWifi();
		        		 wlanManager.setMobileDataEnabled(true);
		        		 while(!connected) {
		        			 if(wlanManager.checkNetworkType() == 5){
				                	connected = true;
				                	wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
				                }
		        		 }
		        	 } else {
		        		 wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
		        	 } 
		           }  
		       };

	    	thread.start(); 
	    }
  
    private void upload() {
//    	if(task.scanResult != null && task.scanResult.SSID.equals(WlanManager.SSID_CMCC)){
//			WebAuthManager wManager = new WebAuthManager(ctx);
//			String  defaultUrl = ctx.getResources().getString(R.string.default_url);
//	        DBManager db = new DBManager(ctx);
//			Account config = db.getAccount();
//			String userName ="",pwd="";
//			if(null != config){ 
//				userName = config.userName;
//				pwd = config.password;
//			}
//			wManager.auth(defaultUrl, userName, pwd);
//		 	db.release();
//		}
    	task.endTime = StringUtils.getDateTime(); 
    	if(cameraFlag == null || !cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) {
    		long creatTime = System.currentTimeMillis();
        	 fileName = new CreateResultXML(creatTime).CreateGSM_TDxml(task, ctx);
	    	 ctx.getIntent().putExtra("xml", fileName);
	         DBManager db = new DBManager(ctx);
	         db.saveTask(task.mac, task.apName, String.valueOf(task.id));
	         db.release();
	         if (null != fileName) {
	             showMessage(ctx, "正在上传测试结果...");
	             new Thread() {
	                 public void run() {
	                     if (uplod(fileName, ctx, handler))
	                         fileName = null;
	                 }
	             }.start();
	         }
    	} else if(cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) {
    		
    	}
    		
    }

    private void createResultXML() {
        task.endTime = StringUtils.getDateTime();
        TaskParser parser = new PullTaskParser();
        if(task.selNetType == ConnectivityManager.TYPE_WIFI){
        	fileName=parser.CreateWLANxml(task,ctx);
        }else if(task.selNetType ==ConnectivityManager.TYPE_MOBILE){
        	fileName=parser.CreateGSMxml(task,ctx);
        }else if(task.selNetType ==ConnectivityManager.TYPE_MOBILE_MMS){
        	fileName=parser.CreateTDxml(task,ctx);
        }else {
			
		}
        
    //    fileName = parser.XmlFileCreator(task);
        ctx.getIntent().putExtra("xml", fileName);
        DBManager db = new DBManager(ctx);
        db.saveTask(task.mac, task.apName, String.valueOf(task.id));
        db.release();
        if (null != fileName) {
            showMessage(ctx, "正在上传测试结果...");
            new Thread() {
                public void run() {
                    if (uplod(fileName, ctx, handler))
                        fileName = null;
                }
            }.start();
        }
        ctx.getIntent().removeExtra(TAG_REFER_TASK);
    }
   private void show() {
        
        float m , n;
        DecimalFormat df = new DecimalFormat("#0.000");
        TextView t = new TextView(ctx);
        StringBuffer s = new StringBuffer();  
    	//HTTP测试  
 
        s.append("平均时延：").append(df.format(StringUtils.parseFloat(task.httpAnwerDelay))).append(" s").append('\n');
        s.append("访问成功率：").append(task.httpCallSuccessRate).append(" %");
            t.setTextColor(Color.WHITE);
            t.setText(s);
            httptaskLayout.addView(t);
   	

      //FTP测试   (都有)
        s = new StringBuffer();
        float tempUpAvg = Float.parseFloat(task.ftpUpAvgSuccessRate) * 8;
        float tempDownAvg = Float.parseFloat(task.ftpDownAvgSuccessRate) * 8;
        s.append("平均上传速度：").append(tempUpAvg).append(" Kb/s").append('\n');
        s.append("平均下载速度：").append(tempDownAvg).append(" Kb/s").append('\n');
        m = (float) StringUtils.parseFloat(task.ftpUpCount);
        n = (float) StringUtils.parseFloat(task.ftpUpSuccessCount);
        s.append("上传成功率：").append(m==0?0:df.format( 100*n / m)).append(" %").append('\n');
        m = (float) StringUtils.parseFloat(task.ftpDownCount);
        n = (float) StringUtils.parseFloat(task.ftpDownSuccessCount);
        s.append("下载成功率：").append(m==0?0:df.format( 100*n / m)).append(" %");
        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        ftptaskLayout.addView(t);

      //PING 测试   (都有)
        s = new StringBuffer();
  	   s.append("平均时延：").append(df.format((float) StringUtils.parseFloat(task.pingAvgDelay))).append(" s").append('\n');
         m = (float) StringUtils.parseFloat(task.pingCount);
         n = (float) StringUtils.parseFloat(task.pingSuccessCount);
         s.append("丢包率：").append(m==0?0:df.format( 100*(m-n) / m)).append(" %");
        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        pingtaskLayout.addView(t);
 
        	//snr 测试   (都有)
            /*s = new StringBuffer();
            s.append("SNR：").append(task.snr);
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            snrtaskLayout.addView(t); */
  
      //rssi 测试   (都有)
        s = new StringBuffer();
        s.append("CI：").append(task.ci);
        s.append("\nLAC：").append(task.lac);  
        String rssi = task.rssi.equals("0")?"0":"-"+task.rssi;
        s.append("\n信号强度：").append(rssi).append(" dBm");

        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        rssitaskLayout.addView(t);
        showTaskNum();
    }
    private void showTaskNum() {
        int infoSize = ctx.getIntent().getIntExtra("info", 0);
        if (infoSize > 0) {
            DBManager db = new DBManager(ctx);
            List<TaskConfig> configs = db.getTask(task.apName, String.valueOf(task.id));
            db.release();
            StringBuffer s = new StringBuffer();
            s.append("已完成此热点下  ").append(configs.size()).append(" 项测试.");
            s.append("还剩 ").append(infoSize - configs.size()).append(" 项.");
            TextView tv = new TextView(ctx);
            tv.setText(s);
            tv.setTextSize(14);
            tv.setTextColor(Color.CYAN);
            taskNumLayout.addView(tv);
        }
    }
    public void showCameraDialog(final Activity ctx) { 
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);  
        	builder.setTitle("拍照提示");   
        	builder.setMessage("是否进行测试现场拍照？");
        	builder.setCancelable(true);
     		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
     			public void onClick(DialogInterface dialog, int id) {
                	GlobalApp.who_to_CameraWidget = MessageWhat.TaskResultTD;
                   CameraWidget cw = new CameraWidget(ctx);
                   ctx.setContentView(cw);
     			}
     		}); 
     		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
             	public void onClick(DialogInterface dialog, int id) {
             		try {
     					Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
     					field.setAccessible(true);
     					field.set(dialog, true);
     				} catch (Exception e) {
     					e.printStackTrace();
     				}
             		dialog.cancel();
             	}
             });
     		wifiListDialog = builder.create();
            wifiListDialog.show();
		  
    }
	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}
	public Task dealWebAndPeapData(Task task){
		if(task==null || task.scanResult==null || task.scanResult.SSID==null || !task.scanResult.SSID.equals(WlanManager.SSID_CMCC)){
			task.webDelay = "-1";
			task.webOffSuccessRate="-1";
			task.webSuccessRate = "-1";
		} 
		if(task==null || task.scanResult==null || task.scanResult.SSID==null || !task.scanResult.SSID.equals(WlanManager.SSID_CMCC_AUTO)){
			task.peapAuthAvgTime = "-1";
			task.peapDelay="-1";
			task.peapOffSuccessRate = "-1";
			task.peapSuccessRate = "-1";
		}
		return task;
	}
}
